package com.eneat.smartrule.util;


import cn.hutool.core.util.ObjUtil;
import com.eneat.smartrule.model.ArithmeticExpression;
import com.eneat.smartrule.model.Rule;
import com.eneat.smartrule.model.RuleCondition;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ExpressionUtil {

    public static String buildStatement(Rule rule) {
        String expression = "";
        if (ObjUtil.isNotNull(rule.getExpression()) && !rule.getExpression().isEmpty()) {
            expression = rule.getExpression();
        } else {
            expression = buildExpression(rule.getRuleConditions());
        }
        return expression;
    }

    public static String buildExpression(List<RuleCondition> ruleConditions) {
        StringBuilder expressionBuilder = new StringBuilder();

        // 判断是否存在action有值的condition
        long actionNum = ruleConditions.stream().filter(condition -> ObjUtil.isNotEmpty(condition.getRuleAction())).count();
        if (actionNum > 0) {
            expressionBuilder.append("if (");
        }

        for (int i = 0; i < ruleConditions.size(); i++) {
            RuleCondition ruleCondition = ruleConditions.get(i);

            if (ObjUtil.isNotEmpty(ruleCondition.getExpression())) {

                expressionBuilder.append("(").append(ruleCondition.getExpression()).append(")");

                if (ObjUtil.isNotEmpty(ruleCondition.getLogic())) {
                    expressionBuilder.append(" ").append(ruleCondition.getLogic().getCode()).append(" ");
                }

            } else {

                // 如果需要括号，添加左括号
                if (ruleCondition.isBracketed()) {
                    expressionBuilder.append("(");
                }

                // 处理子条件
                if (ruleCondition.getSubRuleConditions() != null && !ruleCondition.getSubRuleConditions().isEmpty()) {
                    expressionBuilder.append(buildExpression(ruleCondition.getSubRuleConditions()));
                }

                // 动态拼接前缀
                String prefixedField = ruleCondition.getPrefix() != null ? ruleCondition.getPrefix() + ruleCondition.getField() : ruleCondition.getField();


                // 处理算术表达式或单一条件
                if (ruleCondition.getArithmeticExpressions() != null && !ruleCondition.getArithmeticExpressions().isEmpty()) {
                    for (int j = 0; j < ruleCondition.getArithmeticExpressions().size(); j++) {
                        ArithmeticExpression arithmeticExpression = ruleCondition.getArithmeticExpressions().get(j);

                        // 如果是第一个操作数，直接添加
                        if (j > 0 && arithmeticExpression.getArithmeticOperator().getCode() != null) {
                            expressionBuilder.append(" ").append(arithmeticExpression.getArithmeticOperator().getCode()).append(" ");
                        }
                        expressionBuilder.append(arithmeticExpression.getOperand());
                    }
                    // 添加比较运算符和值
                    expressionBuilder.append(" ")
                            .append(ruleCondition.getOperator().getCode())
                            .append(" ")
                            .append(ruleCondition.getIsValueQuoted() ? "'" + String.join(", ", ruleCondition.getFieldValue()) + "'" : String.join(", ", ruleCondition.getFieldValue()));
                } else if (ruleCondition.getField() != null) {

                    if (ruleCondition.getCustomFunction() != null && !ruleCondition.getCustomFunction().isEmpty()) {
                        // 使用自定义函数，确保格式为 field operator function(value)
                        expressionBuilder.append(prefixedField)
                                .append(" ")
                                .append(ruleCondition.getOperator().getCode())
                                .append(" ")
                                .append(ruleCondition.getCustomFunction())
                                .append("(")
                                .append(ruleCondition.getIsValueQuoted() ? "'" + String.join(", ", ruleCondition.getFieldValue()) + "'" : String.join(", ", ruleCondition.getFieldValue()))
                                .append(")");
                    } else {

                        // 普通的操作符逻辑
                        expressionBuilder.append(prefixedField)
                                .append(" ")
                                .append(ruleCondition.getOperator().getCode())
                                .append(" ")
                                .append(ruleCondition.getIsValueQuoted() ? "'" + String.join(", ", ruleCondition.getFieldValue()) + "'" : String.join(", ", ruleCondition.getFieldValue()));
                    }
                }

                // 如果需要括号，添加右括号
                if (ruleCondition.isBracketed()) {
                    expressionBuilder.append(")");
                }

                // 添加逻辑操作符
                if (i < ruleConditions.size() - 1 && ruleCondition.getLogic() != null) {
                    expressionBuilder.append(" ").append(ruleCondition.getLogic().getCode()).append(" ");
                }
            }
            // 添加逻辑操作符
            if (i < ruleConditions.size() - 1) {
                RuleCondition nextRuleCondition = ruleConditions.get(i + 1);
                if (nextRuleCondition.getRuleAction() != null) {
                    expressionBuilder.append(")")
                            .append(" { return ")
                            .append(nextRuleCondition.getRuleAction().getTargetType() == Boolean.class ? nextRuleCondition.getRuleAction().getTarget() : "'" + nextRuleCondition.getRuleAction().getTarget() + "'")
                            .append("; }")
                            .append(" elsif (");
                }
            }
        }
        String result;
        if (expressionBuilder.charAt(expressionBuilder.length() - 1) == '(' && expressionBuilder.length() > 8) {
            result = expressionBuilder.substring(0, expressionBuilder.length() - 8);
        } else {
            result = expressionBuilder.toString().trim();
        }

        return result;
    }

}
